package jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * jdbcApi之connection,事务管理
 */
public class ConnectionDemo {
    public static void main(String[] args) throws Exception {
        //注册驱动
        Class.forName("com.mysql.jdbc.Driver");
        //获取链接,如果是本机数据库且端口3306可以省略不写
        String url = "jdbc:mysql:///db1?useSSL=false";
        String userName = "root";
        String password = "123456";
        Connection con = DriverManager.getConnection(url,userName,password);
        //写sql语句
        String sql1 = "update account set money=3000 where id=1";
        String sql2 = "update account set money=3000 where id=2";
        //获取执行sql语句的对象
        Statement stmt = con.createStatement();

        try {
            //开始事务=============
            //关闭自动提交
            con.setAutoCommit(false);
            //执行sql语句并获取返回值处理
            int count = stmt.executeUpdate(sql1);
            System.out.println(count);
            //制造一个异常使后面的代码无法执行
            int i = 3/0;
            int count2 = stmt.executeUpdate(sql2);
            System.out.println(count2);

            //运行到这里说明程序没问题,提交事务
            con.commit();
        } catch (Exception e) {
            con.rollback();
            e.printStackTrace();
        } finally {
            stmt.close();
            con.close();
        }
    }
}
